# 导入 flask 和 flask_sqlalchemy

import yaml
from flask import Flask, request
from flask_restx import Api, Resource, Namespace
from flask_sqlalchemy import SQLAlchemy
# 实例化app 对象
from sqlalchemy import *

from back_live1.utils.log_utils import logger

app = Flask(__name__)
api =Api(app)
case_ns = Namespace("case",description="用例管理")

with open("./data/data.yaml") as f:
    result = yaml.safe_load(f)
    username = result.get("database").get('username')
    password = result.get("database").get('password')
    server = result.get("database").get('server')
    db = result.get("database").get('db')

app.config['SQLALCHEMY_DATABASE_URI'] = \
    f"mysql+pymysql://{username}:{password}@{server}/{db}?charset=utf8"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# SQLAlchemy 绑定 app
db = SQLAlchemy(app)

# 用例表
class TestCase(db.Model):
    __tablename__ = "testcase"
    # 用例ID，用例的唯一标识
    id = Column(Integer, primary_key=True)
    # 用例的标题或者文件名
    case_title = Column(String(80), unique=True, nullable=False)
    # 备注
    remark = Column(String(120))

@case_ns.route("")
class TestCaseServer(Resource):
    get_parser = api.parser()
    get_parser.add_argument("id", type=int, location="args")

    @case_ns.expect(get_parser)
    def get(self):
        case_id = request.args.get("id")
        logger.info(f"接收到的参数：{case_id}")

        if case_id :
            case_data = TestCase.query.filter_by(id=case_id).first()
            logger.info({case_data.case_title})
            if case_data:
                datas = [{"id":case_data.id,
                          "case_title":case_data.case_title,
                          "remark":case_data.remark}]
            else:
                datas = []
        else:
            case_datas = TestCase.query.all()
            datas = [{"id":case_data.id,
                      "case_title":case_data.case_title,
                      "remark":case_data.remark}
                     for case_data in case_datas]
        return datas

    post_parser = api.parser()
    post_parser.add_argument("id",type=int,required=True,location="json")
    post_parser.add_argument("case_title",type=str,required=True,location="json")
    post_parser.add_argument("remark",type=str,location="json")

    @case_ns.expect(post_parser)
    def post(self):
        case_data = request.json
        logger.info(f"接收到的参数：{case_data}")
        case_id = case_data.get("id")
        exists = TestCase.query.filter_by(id=case_id).first()
        logger.info((f"查询结果：{exists}"))

        if not exists:
            testcase = TestCase(**case_data)
            logger.info(f"入库数据：{testcase}")
            db.session.add(testcase)
            db.session.commit()
            return {"code":0,"msg":f"case id {case_id} sucess add."}
        else:
            return {"code":4001,"msg":f"case id exists."}

    put_parser = api.parser()
    put_parser.add_argument("id",type=int,required=True,location="json")
    put_parser.add_argument("case_title", type=str, required=True, location="json")
    put_parser.add_argument("remark", type=str, location="json")

    @case_ns.expect(put_parser)
    def put(self):
        case_data = request.json
        case_id = case_data.get("id")
        logger.info(f"接收到的id：{case_id}")
        exists = TestCase.query.filter_by(id=case_id).first()

        if exists:
            case_data1 = {}
            case_data1["case_title"] = case_data.get("case_title")
            case_data1["remark"] = case_data.get("remark")
            TestCase.query.filter_by(id=case_id).update(case_data1)
            db.session.commit()
            return {"code":0,"msg":f"case id {case_id} sussess updata"}
        else:
            return {"code":40002,"msg":f"case id {case_id} not exists"}


    delete_parser = api.parser()
    delete_parser.add_argument("id",type=int,required=True,location="json")

    @case_ns.expect(delete_parser)
    def delete(self):
        case_data = request.json
        case_id = case_data.get("id")
        logger.info(f"接受到的id：{case_id}")
        exists = TestCase.query.filter_by(id=case_id).first()

        if exists:
            TestCase.query.filter_by(id=case_id).delete()
            db.session.commit()
            return {"code": 0, "msg": f"case id {case_id} sucess delete"}

        else:
            return {"code": 40002, "msg": f"case id {case_id} not exists"}


api.add_namespace(case_ns,"/testcase")

if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)